<?php
class CliFlowerController extends BpfController
{
  public function itemCLI()
  {
    $mysqlModel = $this->getModel('mysql');
    $mysqlModel->query(join(' ', [
      'INSERT INTO `players` (`player_id`, `openid`,`flowers_items`) (',
      '  SELECT `stores_items`.`store_id` AS `player_id` , "" AS `openid`, sum(`items`.`income`) AS `flowers_items`',
      '  FROM `stores_items`',
      '  INNER JOIN `items` ON `items`.`item_id` = `stores_items`.`item_id`',
      '  GROUP BY `stores_items`.`store_id`',
      ') ON DUPLICATE KEY UPDATE `flowers_items` = `flowers_items` + VALUES(`flowers_items`)'
    ]));
  }

  public function childrenCLI()
  {
    $mysqlModel = $this->getModel('mysql');
    //获取昨日的开始时间戳
    $starttime = mktime(0, 0, 0, date('m'), date('d') -1 , date('Y'));
    $endtime = $starttime + 86400;
    $created = REQUEST_TIME;
    $mysqlModel->query(join(' ', [
      'INSERT IGNORE INTO `players_children_flowers` (`player_id`, `child_id`, `date`, `flowers`, `created`, `updated`)',
      'SELECT ',
      " `player_id`, `child_id`, `date`, `income` AS `flowers`, ${created} AS `created`, ${created} AS `updated` from (",
      '  SELECT',
      '    `players`.`parent_id` as `player_id`,',
      '    `players`.`player_id` as `child_id`,',
      '    from_unixtime(`players_flowers_logs`.`created`, "%Y%m%d") AS `date`,',
      '    FLOOR(SUM(`players_flowers_logs`.`flowers` * 0.05)) AS `income`',
      '  FROM `players_flowers_logs`',
      '  INNER JOIN `players` ON `players`.`player_id` = `players_flowers_logs`.`player_id`',
      '  WHERE',
      '  `players`.`parent_id` > 0 AND',
      '  `players_flowers_logs`.`op` = "商品收益" AND',
      "   `players_flowers_logs`.`created` BETWEEN ${starttime} AND ${endtime}",
      '  GROUP BY `date`, `child_id`, `player_id`',
      ' ) `children_incomes`',
      'WHERE `income` > 0',
    ]));
  }

  public function settlePlayerItemCLI()
  {
    $playerModel = $this->getModel('player');
    do {
      $players = $playerModel->getPlayersList(['flowers_items gte' => 1, 1, 20]);
      foreach ($players as $player) {
        $player->settleItemFlower();
      }
    } while ($players[0] ?? false);
  }

}
